package cn.hnzzs.canal;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import com.alibaba.otter.canal.protocol.Message;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Created by Alan on 2017/3/30.
 */
public class SimpleCanalClientExample {

    private static Logger logger = Logger.getLogger(SimpleCanalClientExample.class);

    private static String DB_USERNAME = "canal";
    private static String DB_USERPASS = "canal";

    private static String CANAL_URL = "10.73.161.134";
//    private static String CANAL_URL = "192.168.10.106";

    public static void main(String args[]) throws SQLException, ClassNotFoundException {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(CANAL_URL,
                11111), "example", "", "");
        int batchSize = 1000;
        try {
            connector.connect();
            connector.subscribe("quying_wd.test");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                System.out.println("waiting...");
                if (batchId == -1 || size == 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    printEntry(message.getEntries());
                }

                connector.ack(batchId); // 提交确认
            }
        } finally {
            connector.disconnect();
        }
    }

    private static void printEntry(List<Entry> entrys) throws SQLException, ClassNotFoundException {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }

            RowChange rowChange = null;

            try {
                rowChange = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {

                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);

            }

            EventType eventType = rowChange.getEventType();
            String tableName = entry.getHeader().getTableName();
            System.out.println(String.format("================> binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));

            for (RowData rowData : rowChange.getRowDatasList()) {
                if (eventType == EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                } else if (eventType == EventType.INSERT) {
                    //insertData(rowData.getAfterColumnsList(), tableName);
                    printColumn(rowData.getAfterColumnsList());
                } else {
                    System.out.println("-------> before");
                    printColumn(rowData.getBeforeColumnsList());
                    System.out.println("-------> after");
                    printColumn(rowData.getAfterColumnsList());
                }
            }
        }
    }


    private static void insertData(List<Column> columns, String tableName) throws SQLException, ClassNotFoundException {
        StringBuilder execSql = new StringBuilder("INSERT INTO ");
        StringBuilder placeHolder = new StringBuilder();
        execSql.append(tableName).append(" (");

        for (Column column : columns) {
            System.out.println(column.getSqlType());
            execSql.append(column.getName());
            execSql.append(",");

            placeHolder.append("?");
            placeHolder.append(",");

        }
        execSql.deleteCharAt(execSql.length() - 1);
        execSql.append(") VALUES(");
        placeHolder.deleteCharAt(placeHolder.length() - 1);
        execSql.append(placeHolder);
        execSql.append(");");
        System.out.println(execSql);

        Connection con = getConnection();
        PreparedStatement pt = con.prepareStatement(execSql.toString());
        for (int i = 1; i <= columns.size(); i++) {
            Column column = columns.get(i - 1);
            if (null == column.getValue()) {
                pt.setNull(i, column.getSqlType());
            } else {
                pt.setObject(i, column.getValue(), column.getSqlType());
            }
        }
        pt.executeUpdate();
        con.close();
    }

    private static void printColumn(List<Column> columns) {
        for (Column column : columns) {

            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());

        }
    }

    private static Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://10.73.161.240:3306/hello", DB_USERNAME, DB_USERPASS);
    }
}
